package com.youhong.teethcare.customviews

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.youhong.teethcare.R
import com.youhong.teethcare.utils.ScreenUtils
import java.util.*

class BatteryView : View {

    var bitmapBackground: Bitmap? = null
    lateinit var mPaint: Paint;
    private var batteryValue: Int = 100;

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init(context)
    }

    fun init(context: Context?) {
        bitmapBackground = BitmapFactory.decodeResource(resources, R.drawable.dashbord_battery)
        mPaint = Paint();
        mPaint?.isAntiAlias = true;
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}

    fun updateBatteryValue(batteryValue: Int) {
        this.batteryValue = batteryValue
        postInvalidate()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        drawBackground(canvas)
        drawBattery(canvas)
    }

    fun drawBattery(canvas: Canvas) {
        var color = when (batteryValue > 20) {
            true -> Color.BLACK
            else -> Color.RED
        }
        mPaint.color = color
        val top = (height-bitmapBackground!!.height)/2
        val bottom=top+bitmapBackground!!.height;
        val left=(width-bitmapBackground!!.width)/2
        var rect = RectF();
        rect.top = top+4f;
        rect.bottom = bottom - 4f;
        rect.left = left+6f;
        rect.right =rect.left+(bitmapBackground!!.width- ScreenUtils.dip2px(context, 7f))*(batteryValue/100f)
        canvas.drawRect(rect, mPaint);
    }

    fun drawBackground(canvas: Canvas) {
        drawBitmap(canvas, bitmapBackground)
    }

    fun drawBitmap(canvas: Canvas, bitmap: Bitmap?) {
        val left=(width-bitmapBackground!!.width)/2
        val top = (height-bitmap!!.height)/2
        canvas.drawBitmap(bitmap!!, left.toFloat(), top.toFloat(), null)
    }





}